package com.wzm.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import com.wzm.manager.AppConfig;

public class FileUtils {
    private static final int BUFFER = 8192;
    //读取文件
    public static String readTextFile(File file) throws IOException {
        String text = null;
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            text = readTextInputStream(is);;
        } finally {
            if(is != null) {
                is.close();
            }
        }
        return text;
    }

    //从流中读取文件
    public static String readTextInputStream(InputStream is) throws IOException {
        StringBuffer strbuffer = new StringBuffer();
        String line;
        BufferedReader reader = null;
        try{
            reader = new BufferedReader(new InputStreamReader(is));
            while((line = reader.readLine()) != null) {
                strbuffer.append(line).append("\r\n");
            }
        } finally {
            if(reader != null) {
                reader.close();
            }
        }
        return strbuffer.toString();
    }

    //将文本内容写入文件
    public static void writeTextFile(File file, String str) throws IOException {
        DataOutputStream out = null;
        try {
            out = new DataOutputStream(new FileOutputStream(file));
            out.write(str.getBytes());
        } finally {
            if(out != null) {
                out.close();
            }
        }
    }

    //复制文件
    public static void copyFile(File sourceFile, File targetFile)
            throws IOException {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
            inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
            byte[] buffer = new byte[BUFFER];
            int length;
            while ((length = inBuff.read(buffer)) != -1) {
                outBuff.write(buffer, 0, length);
            }
            outBuff.flush();
        } finally {
            if(inBuff != null) {
                inBuff.close();
            }
            if(outBuff != null) {
                outBuff.close();
            }
        }
    }
    
    public static boolean downFile(String url,String savePath)
    {
    	boolean isTrue = false;
    	String savename =  url.substring(url.lastIndexOf("/")+1);
    	String saveDirPath = savePath;
		File movieDir = new File(saveDirPath);
		
		//创建文件夹
		if(!movieDir.exists())
		{
			movieDir.mkdirs();
		}else{
			if(!movieDir.isDirectory())
			{
				movieDir.mkdirs();
			}
		}
		//
		File targetFile = new File(saveDirPath+savename);
		Logger.error(saveDirPath+savename);
		if(targetFile.exists())
		{
			return true;
		}
    	Logger.info("1111111111");
		for(int i=0;i<3;i++)
		{
			InputStream inputStream = null;
			FileOutputStream outputStream = null;
							

			try {
				URL myuUrl = new URL(url);
				URLConnection connection = myuUrl.openConnection();
				connection.connect();
				inputStream = connection.getInputStream();
				int fileSize = connection.getContentLength();
				
				if(fileSize <= 0){
					Logger.error("文件为大小为0");
				}else{
					
					Logger.info("2222222");
					outputStream = new FileOutputStream(saveDirPath + savename);
					//if(out)
					//存储文件
					byte buf[] = new byte[1024];
					int len = 0;				
					while ((len = inputStream.read(buf)) != -1) {				
						outputStream.write(buf, 0, len);			
					}
					isTrue = true;				
				}			
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				Logger.error("MalformedURLException:"+e.getMessage());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				Logger.error("IOException:"+e.getMessage());
			}finally{
				try {			
					if(inputStream != null&&outputStream != null){
						outputStream.close();
						inputStream.close();
					}
				} catch (Exception e2) {
					
				}
			}
			if(isTrue)
			{
				break;
			}else{
				Logger.error("重试"+i);
			}
		}
    	return isTrue;
    }
    
    
    /**
	* 加载本地图片
	* http://bbs.3gstdy.com
	* @param url
	* @return
	*/
	public static Bitmap getLoacalBitmap(String url) {
		
		 FileInputStream fis = null;
	     try {
	          fis = new FileInputStream(url);
//	          BitmapFactory.Options opts = new BitmapFactory.Options();  
//	          opts.inJustDecodeBounds = true;  
	          return BitmapFactory.decodeStream(fis);
	     } catch (FileNotFoundException e) {
	          //e.printStackTrace();
	    	  Logger.info("获取本地文件失败:"+e.getMessage());
	          return null;
	     }finally{
	    	 try {
	    		 if(fis!=null)
	    		 {
	    			 fis.close();
	    		 }				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	     }
	}
	
	
	/**
     * Deletes the directory passed in.
     * @param dir Directory to be deleted
     */
    public static boolean DeleteMovieDir(String movieid) {

    	boolean issuc = false;
    	String dir = Environment.getExternalStorageDirectory().getPath()+AppConfig.MOVIESDIR+movieid+"/";
    	File movieDir = new File(dir);
    	if(movieDir.exists())
    	{
    		issuc = deleteDir(movieDir);
    	} 
    	return issuc;
    }

    /**
     * Deletes all files and subdirectories under "dir".
     * @param dir Directory to be deleted
     * @return boolean Returns "true" if all deletions were successful.
     *                 If a deletion fails, the method stops attempting to
     *                 delete and returns "false".
     */
    public static boolean deleteDir(File dir) {

        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        // The directory is now empty so now it can be smoked
        return dir.delete();
    }
    
    
    
    
    public static long getFileSizes(File f) throws Exception{//取得文件大小
        long s=0;
        if (f.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(f);
           s= fis.available();
        } else {
            f.createNewFile();
            System.out.println("文件不存在");
        }
        return s;
    }
    // 递归
    public static long getFileSize(File f)throws Exception//取得文件夹大小
    {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++)
        {
            if (flist[i].isDirectory())
            {
                size = size + getFileSize(flist[i]);
            } else
            {
                size = size + flist[i].length();
            }
        }
        return size;
    }
    
    public static String FormetFileSize(long fileS) {//转换文件大小
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }
	

}
